package com.zyj.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureTaskTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // 模拟分布式下，一次请求api，调用多个服务
        // 获取用户信息：1、获取订单信息；2、获取积分信息；3、拼凑1、2结果，返回

        long startTime = System.currentTimeMillis();

        int userId = 1;

        // 设置 FutureTask
        FutureTask<String> orderFuture = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return getOrderByUserId(userId);
            }
        });
        FutureTask<String> integrationFuture = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return getIntegrationByUserId(userId);
            }
        });

        // 将 FutureTask 交给线程，开启线程，运行
        new Thread(orderFuture).start();
        new Thread(integrationFuture).start();

        // get方法会阻塞，直到call方法执行结束
        String order = orderFuture.get();
        String integration = integrationFuture.get();

        buildResult(order, integration);

        long endTime = System.currentTimeMillis();

        System.out.println("所用时间：" + (endTime - startTime));
    }

    private static String getOrderByUserId(int userId) throws InterruptedException {
        // 模拟查询所用时间
        TimeUnit.SECONDS.sleep(3);
        return "订单信息";
    }

    private static String getIntegrationByUserId(int userId) throws InterruptedException {
        // 模拟查询所用时间
        TimeUnit.SECONDS.sleep(2);
        return "积分信息";
    }

    private static String buildResult(String order, String integration) throws InterruptedException {
        // 模拟操作所用时间
        TimeUnit.SECONDS.sleep(1);
        return order + integration;
    }
}
